package com.ruoyi.project.wework.manager;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.service.SysLoginService;
import com.ruoyi.project.business.common.constant.BusinessConstant;
import com.ruoyi.project.system.entity.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.wework.ConfigProperties;
import com.ruoyi.project.wework.WeworkFacade;
import com.ruoyi.project.wework.apimodel.*;
import com.ruoyi.project.wework.constant.WeworkConstant;
import com.ruoyi.project.wework.request.SyncRequest;
import com.ruoyi.project.wework.request.WeworkLoginRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class WeworkManager {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ConfigProperties configProperties;
    @Autowired
    private WeworkFacade weworkFacade;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysLoginService loginService;

    public ConfigProperties findWeworkConfig() {
        ConfigProperties config = new ConfigProperties();
        config.setAgentId(configProperties.getAgentId());
        config.setCorpid(configProperties.getCorpid());
        config.setRedirecturl(configProperties.getRedirecturl());
        return config;
    }

    public void syncDept(SyncRequest request, Long operatorId, Long tenantId) {
        // 查部门
        // 本地有的做更新 本地没有的做插入
        // 删除的不管，删除的在通知事件处理

        // 考虑做异步.
        String accessToken = getAccessToken();
        DepartmentModel deptListModel = weworkFacade.getDeptListModel(accessToken);
//        String tmpString = "{\"errcode\":0,\"errmsg\":\"ok\",\"department\":[{\"id\":1,\"name\":\"上海云哇哦软件科技有限公司\",\"parentid\":0,\"order\":100000000,\"department_leader\":[]},{\"id\":2,\"name\":\"总部\",\"parentid\":1,\"order\":100000000,\"department_leader\":[]},{\"id\":3,\"name\":\"上海分公司\",\"parentid\":1,\"order\":99999000,\"department_leader\":[]},{\"id\":4,\"name\":\"总部人事部\",\"parentid\":2,\"order\":100000000,\"department_leader\":[]},{\"id\":5,\"name\":\"总部财务\",\"parentid\":2,\"order\":99999000,\"department_leader\":[]}]}";
//        DepartmentModel deptListModel = JSON.parseObject(tmpString, DepartmentModel.class);
        if(deptListModel.isSuccess()) {
            List<Department> department = deptListModel.getDepartment();
            if(request.getMode() == 1) {
                sysDeptService.syncDeptClean(department, BusinessConstant.OutPlatType.WE_WORK, operatorId, tenantId);
            } else {
                sysDeptService.syncDept(department, BusinessConstant.OutPlatType.WE_WORK, operatorId, tenantId);
            }

        } else {
            log.error("读取企业微信部门列表失败");
        }
    }


    public void syncUser(SyncRequest request, Long operatorId, Long tenantId) {
        String weworkDeptId = ""; // TODO
        String accessToken = getAccessToken();
        UserModel model = weworkFacade.getUserListByDeptId(accessToken, weworkDeptId);
        if(model.isSuccess()) {
            List<User> users = model.getUserlist();
//            if(request.getMode() == 1) {
//                sysDeptService.syncDeptClean(users, BusinessConstant.OutPlatType.WE_WORK, operatorId, tenantId);
//            } else {
//                sysDeptService.syncDept(users, BusinessConstant.OutPlatType.WE_WORK, operatorId, tenantId);
//            }

        } else {
            log.error("读取企业微信部门列表失败");
        }
    }


    /**
     * 设计一个定时任务每小时执行一次
     */
    public void refreshAccessToken() {
        if(redisCache.getCacheObject(WeworkConstant.accessTokenKey) == null) {
            String accessTokenJson = weworkFacade.requestAccessToken(configProperties.getCorpid(), configProperties.getSecret());
            AccessTokenModel accessTokenModel = JSON.parseObject(accessTokenJson, AccessTokenModel.class);
            String accessToken = accessTokenModel.getAccess_token();

            redisCache.setCacheObject(WeworkConstant.accessTokenKey, accessToken, 7000, TimeUnit.SECONDS);

            log.info("cached accessToken : {}", accessToken);
        }
    }

    public String getAccessToken() {
        Object cacheObject = redisCache.getCacheObject(WeworkConstant.accessTokenKey);
        if(cacheObject == null) {
            throw new CustomException("系统异常: 企微 accesstoken失效，请刷新 token");
        }
        return cacheObject.toString();
    }


    public String simpleLogin(WeworkLoginRequest request) {
        String code = request.getCode();
        String userId = codeToUserId(code);
        log.info("userId: {}", userId);

        SysUser user = sysUserService.findUsersOfOutUserId(userId, BusinessConstant.OutPlatType.WE_WORK);
        if(user != null) {
            String username = user.getUserName();
            String token = loginService.simpleLogin(username);
            return token;
        }
        throw new CustomException("请先同步企业微信用户", -1);
    }


    public String codeToUserId(String code) {
        // 获取用户id
        String accessToken = getAccessToken();
        UserIdModel model = weworkFacade.getWeworkUserIdByCode(accessToken, code);
        if(model.isSuccess()) {
            return model.getUserid();
        }
        log.error("code 换取 userId 失败 {}, {}", model.getErrcode(), model.getErrmsg());
        throw new CustomException("code 换取 userId 失败");
    }
}
